<?php
namespace App\Console\Commands\Shipping;

use App\Models\Shipping\SSkuApply;
use App\Models\Shipping\SSkuTotal;
use App\Models\Shipping\SSkuTotalApply;
use Illuminate\Console\Command;

class TotalSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shipping:sync-total';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'exe func';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dates = SSkuApply::initShippingDate();
        $path = SSkuTotalApply::getFile();
        $fp = fopen($path, 'a');
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($fp, ['SKUID','DATE','更新前','更新后']);
        //提货汇总
        SSkuTotal::query()
            ->orderBy('id')
            ->chunk(300, function ($items) use (&$fp,$dates){
                foreach ($items as $item){
                    foreach($dates as $date => $label){
                        $approvalNum = SSkuApply::query()
                            ->where('psku_id',$item->psku_id)
                            ->where('shipping_date',$date)
                            ->sum('approval_num');
                        if($approvalNum > 0){
                            //提货汇总申请
                            $sta = SSkuTotalApply::query()
                                ->firstOrNew([
                                    'psku_id' => $item->psku_id,
                                    'shipping_date' => $date
                                ]);
                            $old = $sta->apply_num;
                            if($old != $approvalNum){
                                $sta->apply_num = $approvalNum;
                                $sta->save();
                                fputcsv($fp, [$item->psku_id,$date,$old,$approvalNum]);
                            }
                        }else{
                            SSkuTotalApply::query()
                                ->where('psku_id', $item->psku_id)
                                ->where('shipping_date', $date)
                                ->update(['apply_num' => 0]);
                        }
                    }
                }
            });
        fclose($fp);
        $this->info('finish!');
    }
}
